package com.itheima.job;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ExcelTest {
    public static void main(String[] args) throws IOException {
        //获取excle工作簿对象
        XSSFWorkbook sheets = new XSSFWorkbook(new FileInputStream(new File("F:\\test.xlsx")));
        //获取第几页(工作表)
        XSSFSheet sheetAt = sheets.getSheetAt(0);
        //遍历行数据
        for (Row row : sheetAt) {
            short firstCellNum = row.getFirstCellNum();
            System.out.println(firstCellNum);
            System.out.println(row.getLastCellNum() );
            //遍历单元格数据
            for (Cell cells : row) {
                //System.out.println(cells.getStringCellValue());
            }
        }
        sheets.close();
    }
    @Test
    public void tt(){

    }

    @Test
    public void t1() throws  Exception{
        //获取excel工作簿对象
        XSSFWorkbook sheets = new XSSFWorkbook(new FileInputStream(new File("F:\\test.xlsx")));
        //获取工作表
        XSSFSheet sheetAt = sheets.getSheetAt(0);
        System.out.println(sheetAt.getLastRowNum());
        //遍历工作表
        for (int i = 0; i <=/*获取最后一行 从0开始*/sheetAt.getLastRowNum(); i++) {
            //获取每行数据
            XSSFRow row = sheetAt.getRow(i);
            //遍历单元格
            for (int j = 0; j < /*获取最后一个单元格  从1开始*/row.getLastCellNum(); j++) {
                //获取单元格数据
                XSSFCell cell = row.getCell(j);
                System.out.println(cell);
            }
            System.out.println(row.getLastCellNum());
        }
        sheets.close();
    }

    @Test
    public void t2() throws IOException {
        //创建一个excel对象(工作簿)
        XSSFWorkbook sheets = new XSSFWorkbook();
        //创建工作表
        XSSFSheet sheet = sheets.createSheet("渣女工作簿");
        //创建行数据
        XSSFRow row = sheet.createRow(0);
        List<String> oneList = new ArrayList<>();
        oneList.add("姓名");
        oneList.add("年龄");
        oneList.add("生日");
        //添加单元格
        for (int i = 0; i < oneList.size(); i++) {
            row.createCell(i).setCellValue(oneList.get(i));
        }

        XSSFRow row1 = sheet.createRow(1);
        List<String> oneList1 = new ArrayList<>();
        oneList1.add("我没做");
        oneList1.add("18");
        oneList1.add("45");
        //添加单元格
        for (int i = 0; i < oneList1.size(); i++) {
            row1.createCell(i).setCellValue(oneList1.get(i));
        }
        FileOutputStream out = new FileOutputStream(new File("F:\\aa.xlsx"));
        sheets.write(out);
        sheets.close();
    }
}
